package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;
import com.qk.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.io.IOException;

/**
 *
 * @author sch
 * @version 1.0
 * @since 2025-10-11-10:59
 */
@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {

    private static final String LOGIN_PATH = "/login";
    private static final String TOKEN_HEADER_NAME = "token";

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //将请求对象和响应对象强转为HttpServletRequest和HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //1.获取请求路径,判断是否是登录请求,登录请求放行
        String path = request.getRequestURI();
        log.info("拦截到请求: {}", path);
        boolean isLoginReq = ObjectUtil.equal(path, LOGIN_PATH);
        if (isLoginReq) {
            chain.doFilter(request, response);
            return;
        }
        //2.获取请求头中的令牌,判断是否为空,如果为空直接拦截
       String token= request.getHeader(TOKEN_HEADER_NAME);
        if (ObjectUtils.isEmpty(token)) {
            response.setStatus(401);
            return;
        }
        //3.校验token,判断是否合法
        try {
           Claims claims= JwtUtil.parseToken(token);
           //获取用户信息 TODO
           chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("token校验失败: {}", e.getMessage());
            response.setStatus(401);
            return;
        }

        //4.放行
    }
}
